import Taro from '@tarojs/taro'
import { connect } from 'react-redux'
import profileActions from '@ACTIONS/profile'
import authActions from '@ACTIONS/auth'
import { commonInitUser } from '@UTILS/user'

function withLoginPrev() {
  return function withLoginComponent(Component) {
    // 避免H5兼容异常
    if (Taro.getEnv() !== Taro.ENV_TYPE.WEAPP) {
      return Component
    }

    @connect(({ profile }) => ({
      user: profile.user,
      isVisitor: profile.isVisitor
    }),
    { ...profileActions, ...authActions })
    class WithLogin extends Component {
      async componentDidMount() {
        const { user, isVisitor } = this.props
        !user && await this.initUser()
        if (super.componentDidMount && !isVisitor && user) {
          await super.componentDidMount()
        }
      }

      async componentDidUpdate(prevProps, prevState) {
        const { user, isVisitor } = this.props
        const auto_login = (!isVisitor && prevProps.isVisitor)
          || (user && !prevProps.user && !isVisitor)
        if (auto_login) {
          super.componentDidMount && super.componentDidMount()
          return
        }
        if (!isVisitor) {
          super.componentDidUpdate && super.componentDidUpdate(prevProps, prevState)
        }
      }

      componentWillUnmount() {
        this.setState = () => false // 去除警告
        super.componentWillUnmount && super.componentWillUnmount()
      }

      async initUser() {
        const { dispatchInitUser, dispatchVisitorLogin } = this.props
        commonInitUser(dispatchInitUser, dispatchVisitorLogin)
      }
    }
    return WithLogin
  }
}

export default withLoginPrev
